package no.uib.hplims.tools;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Collection;
import no.uib.hplims.models.Peptide;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.FontFactory;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

public class LabelCreator {

	// Page size converted from mm to PostScript points
	private final float documentHeight = (float) ((279 * 7.2) / 2.54);
	private final float documentWidth = (float) ((216 * 7.2) / 2.54);
	private final float sideMargin = (float) ((18 * 7.2) / 2.54);
	private final float topMargin = (float) ((7 * 7.2) / 2.54);
	private final float bottomMargin = (float) ((5 * 7.2) / 2.54);
	private final float cellHeight = (float) ((15.7 * 7.2) / 2.54);
	private final float padding = (float) ((3 * 7.2) / 2.54);

	public LabelCreator() {

	}

	public File createFile(Collection<Peptide> peptides) {

		System.out.println("Creating labels for " + peptides.size()
				+ " peptides.");

		File f = null;
		// Create document of given size
		Document document = new Document(new Rectangle(documentWidth,
				documentHeight), sideMargin, sideMargin, topMargin, bottomMargin);

		try {
			f = new File("labels.pdf");
			PdfWriter.getInstance(document, new FileOutputStream(f));
			document.open();

			PdfPTable table = new PdfPTable(5);
			table.setWidthPercentage(100);
			table.setHorizontalAlignment(Element.ALIGN_LEFT);

			for (Peptide p : peptides) {
				String info = p.getWellID() + " "
						+ p.getBelongsToOrder().getSalesOrderCode() + " "
						+ p.getUniProtAccession();

				PdfPCell cell = new PdfPCell(new Phrase(info,
						FontFactory.getFont(FontFactory.COURIER, 6)));
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell.setBorder(Rectangle.NO_BORDER);
				cell.setFixedHeight(cellHeight);
				cell.setPadding(padding);

				table.addCell(cell);
			}
			/*
			 * If table row is not completely full, add empty cells to make sure
			 * all cells are displayed in the document.
			 */
			int mod = peptides.size() % 5;
			if (mod != 0) {
				int limit = 5 - mod;
				for (int i = 0; i < limit; i++) {
					PdfPCell cell = new PdfPCell();
					cell.setHorizontalAlignment(Element.ALIGN_CENTER);
					cell.setBorder(Rectangle.NO_BORDER);
					cell.setFixedHeight(cellHeight);
					table.addCell(cell);
				}
			}

			document.add(table);

			document.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return f;
	}

}
